//
//  ViewController.m
//  ThiNhom_iOS
//
//  Created by admin on 5/31/15.
//  Copyright (c) 2015 Huynh Tri Dung. All rights reserved.
//  2d64c4bc219c56f7509860a5afa36fe1

#import "ViewController.h"
#import "DetailViewController.h"
#import "TopCollectionViewCell.h"
#import "CollectionViewCell.h"
#import "DetailViewController.h"

@interface ViewController (){
    NSDictionary *myDictionary;
    int count, currentIndex;
    NSArray *arrRecipe;
}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    NSString* urlString =@"http://food2fork.com/api/search?key=2d64c4bc219c56f7509860a5afa36fe1";
    
    NSURL* url=[[NSURL alloc]initWithString:urlString];
    NSURLRequest* request = [[NSURLRequest alloc]initWithURL:url];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (!connectionError) {
            //NSLog(@"%@",data);
            //NSLog(@"%@",response);
            
            NSError* myError;
            if (!myError) {
                myDictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&myError];
                count = [myDictionary[@"count"] intValue];
                arrRecipe = myDictionary[@"recipes"];
//                NSLog(@"%@", arrRecipe[0]);
                NSLog(@"%@", myDictionary);
                [self.myCollectionView reloadData];
            }
            else{
                NSLog(@"%@",myError);
            }
            

            
            
        }else{
            NSLog(@"connectionError : %@",connectionError);
        }
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UICollectionView Mobile
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
//    
    NSString* IDindentifier=@"";
    TopCollectionViewCell* cell;
    CollectionViewCell* cell2;

    
    if (indexPath.item==0) {
        IDindentifier=@"cell1";
        cell=[collectionView dequeueReusableCellWithReuseIdentifier:IDindentifier forIndexPath:indexPath];
        if (cell==nil) {
            [collectionView registerClass:[TopCollectionViewCell class] forCellWithReuseIdentifier:IDindentifier];
            cell=[collectionView dequeueReusableCellWithReuseIdentifier:IDindentifier forIndexPath:indexPath];
        }
        
        NSDictionary* dictonnary = [[NSDictionary alloc] init];
        dictonnary = [arrRecipe objectAtIndex:indexPath.item];
        
        dispatch_async(dispatch_queue_create("thread", nil), ^{
            NSURL *bgImageURL = [NSURL URLWithString:[dictonnary objectForKey:@"image_url"]];
            NSData *bgImageData = [NSData dataWithContentsOfURL:bgImageURL];
            dispatch_async(dispatch_get_main_queue(), ^{
                UIImage *img = [UIImage imageWithData:bgImageData];
                cell.imageView.image = img;
                
            });
        });
        cell.foodName.text = dictonnary[@"title"];
        cell.foodDescription.text = dictonnary[@"publisher"];
        
        return cell;
    }
    else{
        IDindentifier=@"cell2";
        cell2=[collectionView dequeueReusableCellWithReuseIdentifier:IDindentifier forIndexPath:indexPath];
        if (cell2==nil) {
            [collectionView registerClass:[CollectionViewCell class] forCellWithReuseIdentifier:IDindentifier];
            cell2=[collectionView dequeueReusableCellWithReuseIdentifier:IDindentifier forIndexPath:indexPath];
        }
        
        NSDictionary* dictonnary = [[NSDictionary alloc] init];
        dictonnary = [arrRecipe objectAtIndex:indexPath.item];
        
        dispatch_async(dispatch_queue_create("thread", nil), ^{
            NSURL *bgImageURL = [NSURL URLWithString:[dictonnary objectForKey:@"image_url"]];
            NSData *bgImageData = [NSData dataWithContentsOfURL:bgImageURL];
            dispatch_async(dispatch_get_main_queue(), ^{

                UIImage *img = [UIImage imageWithData:bgImageData];
                cell2.imageView.image = img;
                
            });
        });
        cell2.foodName.text = dictonnary[@"title"];
        return cell2;
    }
    
}


-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.item==0) {
        return CGSizeMake(collectionView.frame.size.width, 165);
    }
    else{
        return CGSizeMake((collectionView.frame.size.width - 10)/2 , 155);
    }
}


 #pragma mark - Navigation

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    DetailViewController *detailView = [segue destinationViewController];
    NSIndexPath* currentIndex = [self.myCollectionView indexPathsForSelectedItems][0];
    detailView.allSearchedFood = arrRecipe;
    detailView.currrentFoodIndex = (int)currentIndex.row;
}


@end
